package app

import (
	"context"
	"fmt"
	"github.com/grpc-ecosystem/grpc-gateway/v2/runtime"
	_ "github.com/mbobakov/grpc-consul-resolver" // It's important
	"google.golang.org/grpc"
	"google.golang.org/grpc/credentials/insecure"
	"log"
	"net/http"
	"start/app/gateway/common"
	userpb "start/gen/user/v1"
	"wmicro/server/httpserver"
	"wmicro/server/httpserver/registrycenter"
)

func Run() error {
	// 多路复用中间件，如令牌校验中间件。
	var sp []runtime.ServeMuxOption

	// 多路复用
	var mux = runtime.NewServeMux(sp...)

	var ctx = context.Background()

	// 代理grpc服务
	var userSrvGrpcConn, err = grpc.Dial(
		fmt.Sprintf("consul://%s/user-srv?wait=14s", common.Config.Consul.Address), //"consul://127.0.0.1:8500/user-srv?wait=14s",
		grpc.WithTransportCredentials(insecure.NewCredentials()),
		grpc.WithDefaultServiceConfig(`{"loadBalancingPolicy": "round_robin"}`),
	)
	if err != nil {
		return err
	}
	if err = userpb.RegisterUserHandler(ctx, mux, userSrvGrpcConn); err != nil {
		return err
	}

	// 实现健康检查接口
	err = mux.HandlePath("GET", "/health", func(w http.ResponseWriter, r *http.Request, pathParams map[string]string) {
		_, _ = w.Write([]byte(string("ok")))
	})
	if err != nil {
		return err
	}

	// 注册中心
	consulRegisterCenter, err := registrycenter.NewConsulRegisterCenter()
	if err != nil {
		log.Printf("服务注册中心创建失败: %s", err.Error())
		return err
	}

	// gateway 服务
	server, err := httpserver.New(
		// 设置服务名称
		httpserver.WithServerOptionName(common.Config.App.Name),
		httpserver.WithServerHttpServer(
			&http.Server{
				Addr:    fmt.Sprintf(":%d", common.Config.App.Port),
				Handler: mux,
			},
		),
		// 设置注册中心
		httpserver.WithServerOptionServiceRegisterHost(common.Config.App.Host),
		httpserver.WithServerOptionServiceRegisterCenter(consulRegisterCenter),
	)
	if err != nil {
		log.Printf("httpServer创建失败: %s", err.Error())
		return err
	}

	return server.Run()
}
